import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User } from '@/types/user'
import { login as apiLogin, register as apiRegister, getUserInfo } from '@/utils/api'

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))

  const isAuthenticated = computed(() => !!token.value)
  const isAdmin = computed(() => user.value?.user_type === 'admin')
  const isMerchant = computed(() => user.value?.user_type === 'merchant')
  const isCustomer = computed(() => user.value?.user_type === 'customer')

  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const clearToken = () => {
    token.value = null
    localStorage.removeItem('token')
  }

  const setUser = (userData: User) => {
    user.value = userData
  }

  const login = async (username: string, password: string) => {
    try {
      const response = await apiLogin(username, password)
      setToken(response.data.access)
      await fetchUserInfo()
      return { success: true }
    } catch (error: any) {
      return { success: false, message: error.response?.data?.detail || '登录失败' }
    }
  }

  const register = async (userData: {
    username: string
    email: string
    password: string
    phone?: string
  }) => {
    try {
      await apiRegister(userData)
      return { success: true }
    } catch (error: any) {
      return { success: false, message: error.response?.data?.detail || '注册失败' }
    }
  }

  const logout = () => {
    user.value = null
    clearToken()
  }

  const fetchUserInfo = async () => {
    if (!token.value) return
    
    try {
      const response = await getUserInfo()
      setUser(response.data)
    } catch (error) {
      logout()
    }
  }

  const initializeAuth = async () => {
    if (token.value) {
      await fetchUserInfo()
    }
  }

  return {
    user,
    token,
    isAuthenticated,
    isAdmin,
    isMerchant,
    isCustomer,
    login,
    register,
    logout,
    fetchUserInfo,
    initializeAuth
  }
})
